package com.example.springboot.controller;

import com.example.springboot.entity.Result;
import com.example.springboot.entity.User;
import io.swagger.annotations.*;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 用户控制器
 */
@Api(tags = "用户管理接口")
@RestController
@RequestMapping("/user")
public class UserController {

    // 模拟数据库
    private static final Map<Long, User> USERS = new ConcurrentHashMap<>();

    static {
        USERS.put(1L, new User(1L, "admin", "123456", 28, "admin@example.com"));
        USERS.put(2L, new User(2L, "zhangsan", "123456", 18, "zhangsan@example.com"));
        USERS.put(3L, new User(3L, "lisi", "123456", 25, "lisi@example.com"));
    }

    @ApiOperation(value = "获取用户列表", notes = "获取系统中的所有用户信息")
    @GetMapping("/list")
    public Result<List<User>> getUserList() {
        List<User> userList = new ArrayList<>(USERS.values());
        return Result.success(userList);
    }

    @ApiOperation(value = "根据ID获取用户", notes = "根据用户ID获取用户详细信息")
    @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long", paramType = "path", example = "1")
    @GetMapping("/{id}")
    public Result<User> getUserById(@PathVariable Long id) {
        User user = USERS.get(id);
        if (user == null) {
            return Result.error(404, "用户不存在");
        }
        return Result.success(user);
    }

    @ApiOperation(value = "创建用户", notes = "创建新用户")
    @ApiResponses({
            @ApiResponse(code = 200, message = "操作成功"),
            @ApiResponse(code = 400, message = "参数错误"),
            @ApiResponse(code = 500, message = "服务器内部错误")
    })
    @PostMapping("/create")
    public Result<User> createUser(@RequestBody User user) {
        if (user.getId() == null) {
            return Result.error(400, "用户ID不能为空");
        }
        if (USERS.containsKey(user.getId())) {
            return Result.error(400, "用户ID已存在");
        }
        USERS.put(user.getId(), user);
        return Result.success(user);
    }

    @ApiOperation(value = "更新用户", notes = "根据用户ID更新用户信息")
    @PutMapping("/update")
    public Result<User> updateUser(@RequestBody User user) {
        if (user.getId() == null) {
            return Result.error(400, "用户ID不能为空");
        }
        if (!USERS.containsKey(user.getId())) {
            return Result.error(404, "用户不存在");
        }
        USERS.put(user.getId(), user);
        return Result.success(user);
    }

    @ApiOperation(value = "删除用户", notes = "根据用户ID删除用户")
    @ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long", paramType = "path", example = "1")
    @DeleteMapping("/{id}")
    public Result<Void> deleteUser(@PathVariable Long id) {
        if (!USERS.containsKey(id)) {
            return Result.error(404, "用户不存在");
        }
        USERS.remove(id);
        return Result.success(null);
    }
}